package com.tian.service.impl.user;

import com.tian.common.enums.LoginTypeEnum;
import com.tian.common.exception.BusinessException;
import com.tian.common.exception.ValidException;
import com.tian.common.util.StringUtil;
import com.tian.dto.user.AuthLoginDto;
import com.tian.entity.ChargeUser;
import com.tian.mapper.ChargeUserMapper;
import com.tian.service.user.AbstractLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;

/**
 * {@code @description:}  用户名+密码登录
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-04-07 16:42
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class NormalLoginProcessorService extends AbstractLoginService {

    @Resource
    private ChargeUserMapper chargeUserMapper;

    @Override
    public int getLoginType() {
        return LoginTypeEnum.NORMAL.getCode();
    }

    @Override
    public void validate(AuthLoginDto authLoginDto) {
        if (StringUtil.isBlank(authLoginDto.getUserName()) || StringUtil.isBlank(authLoginDto.getPassword())) {
            throw new ValidException("帐号或者密码不能为空");
        }
    }

    @Override
    public ChargeUser doProcessor(AuthLoginDto authLoginDto) {
        log.info("开始处理正常登录：{}", authLoginDto.getUserName());
        ChargeUser chargeUser = chargeUserMapper.selectByName(authLoginDto.getUserName());
        if (chargeUser == null) {
            throw new BusinessException("用户名不存在");
        }
        if (!isPasswordMatch(authLoginDto.getPassword(), chargeUser.getPassword())) {
            throw new BusinessException("密码错误");
        }
        return chargeUser;
    }

    private boolean isPasswordMatch(String rawPassword, String encodedPassword) {
        return DigestUtils.md5DigestAsHex(rawPassword.getBytes()).equals(encodedPassword);
    }
}
